package yz;

/**
 * [19. 删除链表的倒数第 N 个结点](https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/) （中等）
 *
 * @Author yangz
 * @Date 2022/11/9 19:12
 */
public class LeetCode19_RemoveNthNodeFromEndOfList {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode node = head;
        int size = 0;
        while (node != null) {
            size++;
            node = node.next;
        }
        int index = size - n;
        if (index == 0) {
            return head.next;
        }
        node = head;
        while (index > 1) {
            index--;
            node = node.next;
        }

        node.next = node.next == null ? null : node.next.next;
        return head;
    }

    static class ListNode {
        int val;
        ListNode next;

        public ListNode() {

        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
